package com.yonyou.brigade.third_parties.ctripBC.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.common.model.ThirdProperty;
import com.yonyou.brigade.third_parties.common.service.IThirdPropertyService;
import com.yonyou.brigade.third_parties.ctripBC.dao.CtripBCUserMapper;
import com.yonyou.brigade.third_parties.ctripBC.model.CtripBCConfig;
import com.yonyou.brigade.third_parties.ctripBC.model.CtripBCUser;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCPublicService;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCUserService;
import com.yonyou.brigade.third_parties.ctripBC.util.CtripBCUserConvertUtil;
import com.yonyou.brigade.util.operateutil.CompareUtils;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 * 携程（大客户）用户服务实现类
 * </p>
 *
 * @author jiangzhf@yonyou.com
 * @since 2018-12-24
 */
@Service
public class CtripBCUserServiceImpl extends ServiceImpl<CtripBCUserMapper, CtripBCUser> implements ICtripBCUserService {

    @Autowired
    private CtripBCUserMapper ctripBCUserMapper;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    @Qualifier("thirdPropertyServiceImpl")
    private IThirdPropertyService thirdPropertyService;

    @Autowired
    @Qualifier("ctripBCPublicServiceImpl")
    private ICtripBCPublicService ctripBCPublicService;

    @Autowired
    private PropUtil propUtil;

    private Logger logger = LoggerFactory.getLogger(CtripBCUserServiceImpl.class);
    // corporationID数据库中不存在
    private String CompareProperties = "dept1,dept2,email,employeeId,mobilePhone,name,rank,rankName,userId,valid,isSendEmail," +
            "corpCardType,resRange,useTRFlag,isBookClass,intlBookClassBlock";

    public void getLoginInfo(String tenant, String org, String phone, String initPage, int tokenType, HttpServletResponse response , BriChannel briChannel , String source) throws IOException {
        List<CtripBCUser> ctripBCUsers = new CopyOnWriteArrayList<>();
        CtripBCConfig config = JSONObject.parseObject(briChannel.getConfig(), CtripBCConfig.class);
        UcUserDto ucUserDtoByPhone = iUserCenterService.listCompleteUcUserByUserMobiles4admin(phone, tenant);
        if(ucUserDtoByPhone == null){
            logger.info("用户中心不存在用户手机号：" + phone);
            response.sendRedirect(propUtil.getNO_ACCESS_URL());
            return;
        }
        List<ThirdProperty> thirdProperties = thirdPropertyService.getThirdPropertyByTenantOrgChannel(tenant, org, ChannelEnum.CTRIPBC.getName());
        CtripBCUser ctripBCUser = CtripBCUserConvertUtil.getCtripBCUser(ucUserDtoByPhone, config.getCorporationId(), tenant, org, thirdProperties, briChannel);
        ctripBCUsers.add(ctripBCUser);
        if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
            ctripBCPublicService.syncCtripBCUsers(ctripBCUsers, config, briChannel);
        }
        if (!BriChannel.SYNCUSER.equals(briChannel.getSyncUser())) {
            if("pc".equals(source)){
                ctripBCPublicService.ssoPCLogin(ucUserDtoByPhone.getPersonCode(), response, config, initPage, tokenType);
                return;
            }
            ctripBCPublicService.ssoMobileLogin(ucUserDtoByPhone.getPersonCode(), response, config, initPage, tokenType);

        } else if (ctripBCUsers != null && ctripBCUsers.size() > 0) {
            ctripBCUser = ctripBCUsers.get(0);
            if("pc".equals(source)){
                ctripBCPublicService.ssoPCLogin(ctripBCUser.getEmployeeId(), response, config, initPage, tokenType);
                return;
            }
            ctripBCPublicService.ssoMobileLogin(ctripBCUser.getEmployeeId(), response, config, initPage, tokenType);
        }
    }

    @Override
    public JSONObject getCtripBCUsersNeedSync(List<CtripBCUser> ctripBCUsers, CtripBCConfig config, String tenantId) {
        JSONObject result = new JSONObject();
        List<CtripBCUser> ctripBCUsersNeedUpdate = new CopyOnWriteArrayList<>();
        List<CtripBCUser> ctripBCUsersNeedInsert = new CopyOnWriteArrayList<>();
        if (!CollectionUtils.isEmpty(ctripBCUsers)) {
            for (CtripBCUser ctripBCUser : ctripBCUsers) {
                // 防止subAccountName为空
                ctripBCUser.setSubaccountName(config.getSubAccountName());
                Wrapper<CtripBCUser> ctripBCUserWrapper = new EntityWrapper<>();
                ctripBCUserWrapper.where("mobile_phone={0}", ctripBCUser.getMobilePhone());
                ctripBCUserWrapper.and("tenant={0}", tenantId);
                List<CtripBCUser> ctripBCUserList = ctripBCUserMapper.selectList(ctripBCUserWrapper);
                if (!CollectionUtils.isEmpty(ctripBCUserList)) {
                    Map<String, Object> compareResult = compareFields(ctripBCUserList, ctripBCUser);
                    if (compareResult != null && compareResult.size() > 0) {
                        ctripBCUser.setId(ctripBCUserList.get(0).getId());
                        ctripBCUsersNeedUpdate.add(ctripBCUser);
                    }
                } else {
                    ctripBCUsersNeedInsert.add(ctripBCUser);
                }
            }
        }
        result.put("ctripBCUsersNeedInsert", ctripBCUsersNeedInsert);
        result.put("ctripBCUsersNeedUpdate", ctripBCUsersNeedUpdate);
        return result;
    }

    private Map<String, Object> compareFields(List<CtripBCUser> ctripBCUsers, CtripBCUser ctripBCUser) {
        Map<String, String> compareMap = new HashMap<>();
        String[] compareFields = CompareProperties.split(",");
        if (compareFields.length > 0) {
            for (String compareField : compareFields) {
                compareMap.put(compareField, "");//此处只需要key值
            }
        }
        return CompareUtils.getModifyContent(ctripBCUsers.get(0), ctripBCUser, compareMap);
    }

}
